# -*- coding: utf-8 -*-
"""
Created on Mon Mar 11 21:38:48 2013

@author: Ago
"""
from PyQt4.QtCore import QSettings
from PyQt4 import QtCore, QtGui
import vtk
from krajec import Krajec
from ui_krajec import Ui_MainWindow

##      Vkopírovat import + dva řádky po úpravě  Qt Designer 
#        
#        from vtk.qt4.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor
#        ##self.gridLayout.setMargin(0)##
#        
#        self.vtkWidget = QVTKRenderWindowInteractor(self.gridLayoutWidget)
#        self.gridLayout.addWidget(self.vtkWidget, 0, 0, 1, 1)        
#        
#        ##self.gridLayout.setObjectName(_fromUtf8("gridLayout"))##
 

class SimpleView(QtGui.QMainWindow,  Ui_MainWindow):
 
    def __init__(self, instSp, parent = None):
        
        QtGui.QMainWindow.__init__(self)        
        self.instSp = instSp
        
        self.setupUi(self)
        self.ren = vtk.vtkRenderer()
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        self.connect(self.rezat, QtCore.SIGNAL("clicked()"), self.onKrajec)
        self.connect(self.upravBaVe, QtCore.SIGNAL("clicked()"), self.nastavVelikost) #self.prebarvitRez       
        self.connect(self.ulozitRezy, QtCore.SIGNAL("clicked()"), self.ulozRez)
        self.connect(self.dial, QtCore.SIGNAL("valueChanged(int)"), self.posunRez)
        #self.connect(self.doubleSpinBox, QtCore.SIGNAL("clicked()"), self.posunRez)
        
        self.openFile = QtGui.QAction(QtGui.QIcon('open.png'), 'Open .Stl', self)
        self.openFile.setShortcut('Ctrl+O')
        self.openFile.setStatusTip('Open new File')
        self.openFile.triggered.connect(self.open)
        self.menubar = self.menuBar()
        self.fileMenu = self.menubar.addMenu('&Model')
        self.fileMenu.addAction(self.openFile) 
        #self.setting()
        self.nastaveni()
        self.krajec()
        
        
    def testK(self):
        print "TestK -OK"
        
    def setInstance(self, insSV):
        self.insSV = insSV
     

        # Nastavení 
    def nastaveni(self):
       # Přečte ze souboru        
        settings = QSettings("data.ini", QSettings.IniFormat)
        rezTl= settings.value('rezTl', type=int)        
        rezPo= settings.value('rezPo', type=int)
        vel= settings.value('vel', type=float)
        pozadiB4 = settings.value('pozadiB4', type=float)
        pozadiB5 = settings.value('pozadiB5', type=float)
        pozadiB6 = settings.value('pozadiB6', type=float)
        modelB1 = settings.value('modelB1', type=float)
        modelB2 = settings.value('modelB2', type=float)
        modelB3 = settings.value('modelB3', type=float)
        
        self.rotateKoef = settings.value('rotateKoef', type = float)
        self.rotateKoefX = settings.value('rotateKoefX', type = float)
        self.rotateKoefY = settings.value('rotateKoefY', type = float)
        print "Nalkoneni koeficient =", self.rotateKoef
        
        # Nastaví hodnoty
        self.rezT.setProperty("value", rezTl)
        self.rezP.setProperty("value", rezPo)
        self.velikost.setProperty("value", vel)
        self.instSp.doubleSpinBox_4.setProperty("value", pozadiB4)
        self.instSp.doubleSpinBox_5.setProperty("value", pozadiB5)
        self.instSp.doubleSpinBox_6.setProperty("value", pozadiB6)
        self.instSp.doubleSpinBox.setProperty("value", modelB1)
        self.instSp.doubleSpinBox_2.setProperty("value", modelB2)
        self.instSp.doubleSpinBox_3.setProperty("value", modelB3)
        #self.casRez = 0.0 # prodleva mezi jednotlivými řezy - pro vizuální kontrolu

        
    def setting(self):   
        # Uloží do souboru
        settings = QSettings("data.ini", QSettings.IniFormat)
        settings.setValue('rezTl', self.rezT.value())
        settings.setValue('rezPo', self.rezP.value())
        settings.setValue('vel', self.velikost.value())
        #settings.setValue('casRez', 0.0)
        #settings.setValue('sirkaT', self.instSp.sirkaT.value())
        #settings.setValue('vyskaT', self.instSp.vyskaT.value())     
        settings.setValue('pozadiB4', self.instSp.doubleSpinBox_4.value())
        settings.setValue('pozadiB5', self.instSp.doubleSpinBox_5.value())
        settings.setValue('pozadiB6', self.instSp.doubleSpinBox_6.value())
        settings.setValue('modelB1', self.instSp.doubleSpinBox.value())
        settings.setValue('modelB2', self.instSp.doubleSpinBox_2.value())
        settings.setValue('modelB3', self.instSp.doubleSpinBox_3.value())
        
    def spustit3D(self):      
        self.model = vtk.vtkCubeSource()
        self.model.SetXLength(60)
        self.model.SetYLength(45)
        self.model.SetZLength(60)
        self.model.Update()
        #rez
        self.cowNormals1 = vtk.vtkPolyDataNormals()
        self.cowNormals1.SetInputConnection(self.model.GetOutputPort())
        self.cowNormals = vtk.vtkTriangleFilter()
        self.cowNormals.SetInputConnection(self.cowNormals1.GetOutputPort())
        
        self.transform = vtk.vtkTransform()
        self.transform.RotateWXYZ(self.rotateKoef,self.rotateKoefX,self.rotateKoefY,0)
        self.transform.Translate(10.0, 5.0, 30.0)
        self.transform.Scale(1, 1, 1)
        self.transF = vtk.vtkTransformPolyDataFilter()
        self.transF.SetInputConnection(self.model.GetOutputPort())
        self.transF.SetTransform(self.transform)
        
        
        self.plane = vtk.vtkPlane()
        self.plane.SetOrigin(0, 0, 5.00) # výška řezu
        self.plane.SetNormal(0, 0.0000001, -0.01)  # keep everything in direction of normal
        xplaneColl = vtk.vtkPlaneCollection()
        xplaneColl.AddItem(self.plane)
        
        self.plane1 = vtk.vtkPlane()
        self.plane1.SetOrigin(0, 0, 4.95) # výška řezu -zobrazení v okně
        self.plane1.SetNormal(0, 0.0000001, 0.01)  # náklon - bez náklonu chyby
        xplaneColl1 = vtk.vtkPlaneCollection()
        xplaneColl1.AddItem(self.plane1)
        
        
        
        self.clip = vtk.vtkClipClosedSurface()
        self.clip.SetClippingPlanes(xplaneColl)
        self.clip.SetInputConnection(self.transF.GetOutputPort()) #(glyphs.GetOutputPort())
        self.clip.SetActivePlaneColor(1.0,1,0)
        self.clip.GenerateFacesOff()
        self.clip.GenerateFacesOn() 
        self.normalsM = vtk.vtkPolyDataNormals()
        self.normalsM.SetInputConnection(self.clip.GetOutputPort())
        self.normalsM.FlipNormalsOn()        
        
        self.clip1 = vtk.vtkClipClosedSurface()
        self.clip1.SetClippingPlanes(xplaneColl1)
        self.clip1.SetInputConnection(self.clip.GetOutputPort())
        #clip1.SetActivePlaneColor(1.0,0,0)
        self.clip1.GenerateFacesOff()
        self.clip1.GenerateFacesOn()         
        
        self.normals = vtk.vtkPolyDataNormals()
        self.normals.SetInputConnection(self.clip1.GetOutputPort())
        self.normals.FlipNormalsOn()
        #normals.FlipNormalsOff()
        
        self.cutMapper = vtk.vtkDataSetMapper()
        self.cutMapper.SetInputConnection(self.normals.GetOutputPort())
        self.cutMapper.ScalarVisibilityOff()
        
        self.MapperM = vtk.vtkDataSetMapper()
        self.MapperM.SetInputConnection(self.normalsM.GetOutputPort())
        self.MapperM.ScalarVisibilityOff()
        
        self.actor = vtk.vtkActor()
        self.actor.SetMapper(self.cutMapper)
        self.actor.GetProperty().SetColor(0,0,1)   # barva modelu    
        
        self.actorM = vtk.vtkActor()
        self.actorM.SetMapper(self.MapperM)
        self.actorM.GetProperty().SetColor(0.1, 0.0, 0.0)
        self.actorM.GetProperty().SetOpacity(0.1)
        
        self.outline = vtk.vtkOutlineFilter()
        self.outline.SetInputConnection(self.transF.GetOutputPort())
        self.outlineMapper = vtk.vtkPolyDataMapper()
        self.outlineMapper.SetInputConnection(self.outline.GetOutputPort())
        
        
        #create outline actor
        self.outlineActor = vtk.vtkActor()
        self.outlineActor.SetMapper(self.outlineMapper)
        self.outlineActor.GetProperty().SetColor(0, 1.0, 0.0)
        #self.outlineActor.GetProperty().SetOpacity(1)
        
        #self.ren.AddActor(self.actor)   # řez 2x (ze zhora - ze spodu)
        #self.ren.AddActor(self.actorM)          
        
        self.cm = vtk.vtkPolyDataMapper()
        self.cm.SetInputConnection(self.transF.GetOutputPort())
        self.ca = vtk.vtkActor()
        self.ca.SetMapper(self.cm)
        self.ca.GetProperty().SetColor(0.0, 1, 0.0) # barva modelu
        self.ca.GetProperty().SetOpacity(0.25)
        self.ren.AddActor(self.ca)  # celý model
        self.ren.AddActor(self.outlineActor)
        
        camera = vtk.vtkCamera()
#        camera.SetClippingRange(1.81325, 90.6627)
#        camera.SetFocalPoint(4.5, 1, 0)
#        camera.SetPosition(4.5, 1.0, 6.73257)
#        camera.SetViewUp(0, 1, 0)
        camera.Zoom(1)
        self.ren.SetActiveCamera(camera)        
        
        
        self.axesActor = vtk.vtkAnnotatedCubeActor();
        self.axesActor.SetXPlusFaceText('R')
        self.axesActor.SetXMinusFaceText('L')
        self.axesActor.SetYMinusFaceText('H')
        self.axesActor.SetYPlusFaceText('F')
        self.axesActor.SetZMinusFaceText('P')
        self.axesActor.SetZPlusFaceText('A')
        self.axesActor.GetTextEdgesProperty().SetColor(1,1,0)
        self.axesActor.GetTextEdgesProperty().SetLineWidth(2)
        self.axesActor.GetCubeProperty().SetColor(0,0,1)
        self.axes = vtk.vtkOrientationMarkerWidget()
        self.axes.SetOrientationMarker(self.axesActor)
        self.axes.SetInteractor(self.iren)
        self.axes.EnabledOn()
        self.axes.InteractiveOff()



        self.ren.SetBackground(1,1,1)
        self.ren.ResetCamera()
        self.iren.Render() #update model view
        
        
    def krajec(self):
        self.krajec = Krajec()
        #self.krajec.foo = self.instSp


        
    def onKrajec(self):
        #self.listWidget.addItem("Vyber .stl model !! ")
        self.casRez= 0
        self.krajec.platek(self.insSV, self.instSp, self.fileName, self.rezT.value(), self.rezP.value(),
                           self.velikost.value(), self.casRez, 
                           self.zmensit.isChecked(),
                           self.instSp.sirkaT.value(), self.instSp.vyskaT.value(), self.instSp.korekceX.value())     
        self.setting()
        
    def prebarvitRez(self):
        self.krajec.onSrovnatSab() 
        
    def nastavVelikost(self):
        print "Velikost nastavena"


        transf = vtk.vtkTransform()
        transf.Translate(-20.0, -17.5, 0.0)
        transf.Scale(1.5, 1.5, 1.5)
        transformFilter = vtk.vtkTransformPolyDataFilter()
        transformFilter.SetTransform(transf)
        transformFilter.SetInputConnection(self.model.GetOutputPort())
        transformFilter.Update()
        self.cm.SetInputConnection(transformFilter.GetOutputPort())
        self.clip.SetInputConnection(transformFilter.GetOutputPort())
        
        self.cutMapper.SetInputConnection(self.normals.GetOutputPort())
        self.MapperM.SetInputConnection(self.normalsM.GetOutputPort())
        self.ren.AddActor(self.actor)   # řez 2x (ze zhora - ze spodu)
        self.ren.AddActor(self.actorM)   
      
        
        self.ren.ResetCamera()
        self.iren.Render()        

    def ulozRez(self):
        #self.listWidget.addItem("Vyber nebo vytvor novou slozku")
        self.slozkaNazev = QtGui.QFileDialog.getExistingDirectory(self, "Open File",
                QtCore.QDir.currentPath()) 
        print  self.slozkaNazev       
        #self.listWidget.addItem("Ukladam rezy")
        print "Ukladam rezy do - Sablony)"
        self.krajec = Krajec()
        self.krajec.ulozit(self.slozkaNazev) 
        
    def posunRez(self):
        
        n = self.dial.value()/3
        #n = self.doubleSpinBox.value()
        n2= n-0.05
        self.plane.SetOrigin(0, 0, n)
        self.plane1.SetOrigin(0, 0, n2)
        self.normals.SetInputConnection(self.clip1.GetOutputPort())
        self.normalsM.SetInputConnection(self.clip.GetOutputPort())
        self.MapperM.Update()
        self.cutMapper.Update()
        self.ren.ResetCamera()

    def open(self):
        #self.listWidget.addItem("Vyber .stl model ! ")
        self.fileName = QtGui.QFileDialog.getOpenFileName(self, "Open File",
                QtCore.QDir.currentPath())
        print self.fileName 
        
        self.model = vtk.vtkSTLReader()
        self.fileName = str(self.fileName)
        self.model.SetFileName(self.fileName)
        self.model.Update()
        self.cowNormals1.SetInputConnection(self.model.GetOutputPort())
        self.cowNormals.SetInputConnection(self.cowNormals1.GetOutputPort())
        
       
        
        self.cm.SetInputConnection(self.model.GetOutputPort())
        self.ren.ResetCamera()
        self.iren.Render() #update model view
        self.nastavVelikost()
                      

 
#if __name__ == "__main__":
#
#    app = QApplication(sys.argv)
#    window = SimpleView()
#    window.show()
#    window.iren.Initialize() # Need this line to actually show the render inside Qt
#    sys.exit(app.exec_())